<script setup lang="ts">
import { reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr'
import type { IAttrValue, IAttrValueSub } from '@/api/product/attr/types'
import { useCategoryStore } from '@/stores/modules/category'
const categoryStore = useCategoryStore()
// 下面卡片切换场景
const scene = ref<number>(0)
// 收集属性值数据
let attrData = reactive<IAttrValue>({
  attrName: '',
  categoryId: '',
  categoryLevel: 3,
  attrValueList: []
})
const addAttr = () => {
  scene.value = 1
  // 初始化值
  Object.assign(attrData, {
    attrName: '',
    categoryId: categoryStore.cate3Id,
    categoryLevel: 3,
    attrValueList: []
  })
}
// 删除属性
const deleteAttr = async (id: number) => {
  const res = await reqDeleteAttr(id)
  if (res.code == 200) {
    ElMessage.success('属性删除成功')
    categoryStore.getAttrInfoList()
  } else {
    ElMessage.error('属性删除失败')
  }
}
const editAttr = (row: IAttrValue) => {
  scene.value = 1
  // Object.assign(attrData, row) // 浅拷贝 修改数据 取消 会显示出bug
  Object.assign(attrData, JSON.parse(JSON.stringify(row))) // 改为深拷贝
}

const cancelBtn = () => {
  scene.value = 0
}

// 添加属性值按钮
const addAttrSub = () => {
  attrData.attrValueList.push({
    valueName: '',
    flag: true
  })
  // 新增项的input获得焦点
  nextTick(() => {
    inputArr.value[attrData.attrValueList.length - 1].focus()
  })
}
// 保存属性值按钮
const saveAttrSub = async () => {
  const result = await reqAddOrUpdateAttr(attrData)
  if (result.code == 200) {
    scene.value = 0
    categoryStore.getAttrInfoList()
    ElMessage.success(attrData.id ? '属性值修改成功' : '属性值添加成功')
  } else {
    ElMessage.error(attrData.id ? '属性值修改失败' : '属性值添加失败')
  }
}
// 属性值表单元素失去焦点的方法
const toLook = (row: IAttrValueSub, $index: number) => {
  // 无输入
  if (row.valueName.trim() == '') {
    attrData.attrValueList.splice($index, 1)
    ElMessage.error('属性值不能为空！')
    return
  }
  // 重复输入
  let repeat = attrData.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrData.attrValueList.splice($index, 1)
    ElMessage.error('属性值不能重复！')
    return
  }

  row.flag = false
}
const toEdit = (row: IAttrValueSub, $index: number) => {
  row.flag = true
  // 点击项的input获得焦点
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
// 输入框聚焦  ref函数式
let inputArr: any = ref([])

watch(
  () => categoryStore.cate3Id,
  () => {
    if (!categoryStore.cate3Id) return
    categoryStore.getAttrInfoList()
  }
)
// 路由跳转 组件销毁前把仓库数据清空
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<template>
  <div>
    <br />
    <Category :scene="scene" />
    <br />
    <el-card>
      <div v-show="scene == 0">
        <el-button type="primary" icon="Plus" :disabled="categoryStore.cate3Id ? false : true" @click="addAttr">添加平台属性</el-button>
        <el-table :data="categoryStore.attrInfoArr" border stripe style="margin: 17px 0">
          <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>
          <el-table-column label="属性名称" prop="attrName" align="center" width="180px"></el-table-column>
          <el-table-column label="属性值名称" align="center" v-slot="{ row }">
            <span v-for="item in row.attrValueList" :key="item.id">
              <el-tag style="margin: 5px">{{ item.valueName }}</el-tag>
            </span>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180px">
            <template #default="{ row }">
              <el-button type="primary" icon="Edit" @click="editAttr(row)" />
              <el-popconfirm :title="`确定删除-${row.attrName}-吗?`" width="180px" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="danger" icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrData.attrName" placeholder="请输入属性名"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" size="default" icon="Plus" :disabled="!attrData.attrName" @click="addAttrSub">添加属性</el-button>
        <el-button size="default" @click="cancelBtn">取消</el-button>
        <el-table :data="attrData.attrValueList" border stripe style="margin: 17px 0">
          <el-table-column type="index" label="序号" align="center" width="80px" />
          <el-table-column label="属性值名">
            <template #default="{ row, $index }">
              <el-input :ref="(vc: any) => (inputArr[$index] = vc)" v-if="row.flag" @blur="toLook(row, $index)" v-model="row.valueName" />
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #default="{ $index }">
              <el-button type="danger" icon="Delete" @click="attrData.attrValueList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button :disabled="!attrData.attrValueList.length" type="primary" size="default" @click="saveAttrSub">保存</el-button>
        <el-button size="default" @click="cancelBtn">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
